package com.qiangesoft.qrcode.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

@Service
public class QRCodeService {

    private static final int QR_CODE_SIZE = 300;
    private static final String LOGO_IMAGE_PATH = "E:\\Desktop\\xgtx.png"; // 替换为你的Logo图片路径

    public byte[] generateQRCodeWithLogo(String qrCodeText) throws WriterException, IOException {
        // 生成二维码
        Map<EncodeHintType, Object> hintMap = new HashMap<>();
        hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrCodeText, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, hintMap);

        // 将二维码转换为BufferedImage
        BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        // 读取Logo图片
        BufferedImage logoImage = ImageIO.read(new File(LOGO_IMAGE_PATH));

        // 创建一个新的BufferedImage，用于合并二维码和Logo
        BufferedImage combinedImage = new BufferedImage(QR_CODE_SIZE, QR_CODE_SIZE, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = (Graphics2D) combinedImage.getGraphics();
        g2d.drawImage(qrCodeImage, 0, 0, null);

        // 计算Logo放置位置（居中）
        int logoWidth = logoImage.getWidth(null);
        int logoHeight = logoImage.getHeight(null);
        int x = (QR_CODE_SIZE - logoWidth) / 2;
        int y = (QR_CODE_SIZE - logoHeight) / 2;

        // 将Logo绘制到二维码上
        g2d.drawImage(logoImage, x, y, logoWidth, logoHeight, null);
        g2d.dispose();

        // 将合并后的图片写入字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(combinedImage, "png", baos);
        return baos.toByteArray();
    }
}